package alex.game.state
{
	import alex.game.playerIO.PlayerIOManager;
	import alex.game.util.GameUtil;
	
	import com.framework.BasicState;
	import com.framework.GG;
	import com.framework.util.Log;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import playerio.Client;
	import playerio.Connection;
	import playerio.PlayerIO;
	import playerio.PlayerIOError;
	
	public class LoginState extends BasicState
	{
		private var affichage:MovieClip;
		
		public function LoginState()
		{
			
		}
		override public function create():void
		{
			display();
			setListeners();
		}
		override public function destroy():void
		{
			//this.affichage.bt_mochi.removeEventListener(MouseEvent.CLICK, bt_login_clicked);
			//this.affichage.bt_guest.removeEventListener(MouseEvent.CLICK, bt_guest_clicked);

			super.destroy();
		}
		private function display():void
		{
			this.affichage = new STATE_LOGIN;
			
			//bt_play = this.affichage.bt_play as BASIC_BUTTON;
			//bt_play.bt_name.text = "Play";
			this.affichage.stop();
			this.addChild(affichage);
			this.affichage.bt_login.libelle.text = "Play";
		}
		private function setListeners():void
		{
			//this.affichage.bt_mochi.addEventListener(MouseEvent.CLICK, bt_login_clicked);
			//this.affichage.bt_guest.addEventListener(MouseEvent.CLICK, bt_guest_clicked);
		}
		private function bt_login_clicked(e:MouseEvent):void
		{
			if(!GG.isSwitching)
			{
				Log.debug(this,"login clicked");
				GG.switchState(new AccueilState());	
			}
		}
		private function bt_guest_clicked(e:MouseEvent):void
		{
			if(!GG.isSwitching)
			{
				Log.debug(this,"Guest clicked");
				this.affichage.gotoAndStop("connecting");
				
				PlayerIOManager.getInstance().addEventListener(PlayerIOManager.PLAYERIO_EVENT_CONNECTED, connectedHandler);
				GameUtil.player.username = "Guest -"+Math.round(Math.random()*1000);
				PlayerIOManager.getInstance().connectToPlayerIO(GameUtil.player.username);

			}
		}
		private function connectedHandler(e:Event):void
		{
			Log.debug(this, "Connected");
			Log.debug(this, "Connecting to the game room");
			
			PlayerIOManager.getInstance().removeEventListener(PlayerIOManager.PLAYERIO_EVENT_CONNECTED, connectedHandler);
			
			GG.switchState(new LobbyState());
		}

	}
}